#include "dicom/upload/cloud_login.h"

#include <gwbase/base/logging.h>

namespace dicom {

Status LoginToEnterpriseCloud(const std::string& server,
                              const std::string& user,
                              const std::string& password, AccessToken* token,
                              int64_t* token_key, std::string* root_dir_id) {
  int64_t surdoc_key = SDBasic::LoginEnt(server, user, password, *token);

  if (surdoc_key == 0) {
    return Status(Status::kOther, "failed to login into surcloud");
  }
  LOG_INFO << "get OAuth token: " << (surdoc_key >= 1 ? "OK" : "ERROR");

  if (token->privatekey.empty() || token->privatekey == "olduser") {
    return Status(Status::kOther, "invalid private key: " + token->privatekey);
  }

  UserSpaceInfo uinfo;
  if (SDBasic::GetUserSpaceInfo(surdoc_key, uinfo) == false) {
    return Status(Status::kOther, "failed to get user info from surcloud");
  }

  *token_key = surdoc_key;
  *root_dir_id = token->root_folder_id;
  if (root_dir_id->empty()) {
    return Status(Status::kOther, "failed to get user root dir ID");
  }

  return Status();
}

Status LoginToPersonalCloud(const std::string& server, const std::string& user,
                            const std::string& password, AccessToken* token,
                            int64_t* token_key, std::string* root_dir_id) {
  int64_t surdoc_key = SDBasic::Login(server, user, password, *token);

  LOG_INFO << "get OAuth token: " << (surdoc_key >= 1 ? "OK" : "ERROR");
  if (surdoc_key == 0) {
    return Status(Status::kOther, "failed to login into surcloud");
  }

  if (token->privatekey.empty() || token->privatekey == "olduser") {
    return Status(Status::kOther, "invalid private key: " + token->privatekey);
  }

  UserSpaceInfo uinfo;
  if (SDBasic::GetUserSpaceInfo(surdoc_key, uinfo) == false) {
    return Status(Status::kOther, "failed to get user info from surcloud");
  }

  *token_key = surdoc_key;
  *root_dir_id = uinfo.rootDirId;
  if (root_dir_id->empty()) {
    return Status(Status::kOther, "failed to get user root dir ID");
  }
  return Status();
}

#if PERSONAL_CLOUD_BACKEND == 1
LoginCloudFunc LoginToCloud = LoginToPersonalCloud;
#else
LoginCloudFunc LoginToCloud = LoginToEnterpriseCloud;
#endif
}
